package cn.com.utt.unms.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SimplePropertyPreFilter;
import cn.com.utt.common.log.doLog;
import cn.com.utt.common.mapper.CustomColumnMapper;
import cn.com.utt.common.mapper.RoleMapper;
import cn.com.utt.common.mapper.UserMapper;
import cn.com.utt.common.mapper.UserRoleMapper;
import cn.com.utt.common.service.TableService;
import cn.com.utt.common.util.LocaleMessageSourceUtil;
import cn.com.utt.common.util.Tips;
import cn.com.utt.common.vo.OrderColumn;
import cn.com.utt.common.vo.RestResult;
import cn.com.utt.common.vo.Role;
import cn.com.utt.common.vo.TableCustomColumn;
import cn.com.utt.common.vo.TableInput;
import cn.com.utt.common.vo.TableOutput;
import cn.com.utt.common.vo.User;
import cn.com.utt.unms.mapper.AccountMapper;
import cn.com.utt.unms.service.AccountService;
import cn.com.utt.unms.vo.AccountInfo;

@Service("accountService")
public class AccountServiceImpl implements AccountService {
	
	@Autowired
    private LocaleMessageSourceUtil messageSourceUtil;

	@Autowired
	private AccountMapper accountMapper;

	@Autowired
	private RoleMapper roleMapper;

	@Autowired
	private UserRoleMapper userRoleMapper;

	@Autowired
	private UserMapper userMapper;
	
	@Autowired
	private CustomColumnMapper customColumnMapper;

	@Autowired
	private TableService tableService;
	
	@Override
	@Transactional
	@doLog(description = Tips.LogAddAccount, key = "#accountInfo.username")
	public RestResult save(AccountInfo accountInfo, long userId) {
		RestResult restResult = new RestResult();
		String remark = accountInfo.getRemark();
		if (remark.length() > 32) {
			restResult.setErrorCode(1);
			restResult.setErrorMsg(messageSourceUtil.getMessage(Tips.RemarkNotGreaterThan32Letters));
			return restResult;
		}
		
		User user = userMapper.queryByUsernameOrEmail(accountInfo.getUsername());
		if (user != null) {
			// 已经注册过
			restResult.setErrorCode(1);
			restResult.setErrorMsg(messageSourceUtil.getMessage(Tips.UsernameExist));
			return restResult;
		}
		
		user = userMapper.queryByUsernameOrEmail(accountInfo.getEmail());
		if (user != null) {
			// 已经注册过
			restResult.setErrorCode(1);
			restResult.setErrorMsg(messageSourceUtil.getMessage(Tips.PhoneExist));
			return restResult;
		}
		
		// 创建账号
		accountMapper.save(accountInfo);
		// 更新权限
		List<Integer> auths = accountInfo.getAuths();
		if (auths == null) {
			auths = new ArrayList<>();
		}
		List<Role> basic = roleMapper.queryBasic();
		for (Role role : basic) {
			auths.add(role.getId());
		}
		for (Integer auth : auths) {
			userRoleMapper.save(auth, accountInfo.getId());
		}
		
		// 添加全部设备列表默认列
		TableCustomColumn tcc = new TableCustomColumn();
		List<OrderColumn> columns = new ArrayList<>();
		String columnArr[] = { "type", "name", "status", "model", "softVer","sn","hardwareVer", "group", "uptime","isFast" };
		int orderArr[] = { 1, 2, 4, 5, 6,24,25, 7, 26,28 };
		for (int i = 0; i < columnArr.length; i++) {
			OrderColumn orderColumn = new OrderColumn();
			orderColumn.setColumn(columnArr[i]);
			orderColumn.setOrder(orderArr[i]);
			columns.add(orderColumn);
		}
		tcc.setTableName("devices_all");
		tcc.setColumns(columns);
		tableService.updateCustomColumn(tcc, accountInfo.getId());
		
		// 添加ap列表默认列
		tcc = new TableCustomColumn();
		columns = new ArrayList<>();
		String columnArr3[] = { "type", "name", "ip", "status", "model", "softVer", "group", "clients","sn", "uptime","isFast" };
		int orderArr3[] = { 1, 2, 3, 4, 5, 6, 7, 8,24, 26,28 };
		for (int i = 0; i < columnArr3.length; i++) {
			OrderColumn orderColumn = new OrderColumn();
			orderColumn.setColumn(columnArr3[i]);
			orderColumn.setOrder(orderArr3[i]);
			columns.add(orderColumn);
		}
		tcc.setTableName("devices_ap");
		tcc.setColumns(columns);
		tableService.updateCustomColumn(tcc, accountInfo.getId());
		
		// 添加路由设备列表默认列
		tcc = new TableCustomColumn();
		columns = new ArrayList<>();
		String columnArr4[] = { "type", "name", "status", "model", "softVer","sn","hardwareVer", "group", "uptime", "aps","isFast" };
		int orderArr4[] = { 1, 2, 4, 5, 6,24,25, 7, 26, 27,28 };
		for (int i = 0; i < columnArr4.length; i++) {
			OrderColumn orderColumn = new OrderColumn();
			orderColumn.setColumn(columnArr4[i]);
			orderColumn.setOrder(orderArr4[i]);
			columns.add(orderColumn);
		}
		tcc.setTableName("devices_router");
		tcc.setColumns(columns);
		tableService.updateCustomColumn(tcc, accountInfo.getId());
		
		// 添加用户状态默认列
		tcc = new TableCustomColumn();
		columns = new ArrayList<>();
		String columnArr1[] = { "hostname", "ip", "mac", "group", "bssid", "ssid", "uptime" };
		int orderArr1[] = { 1, 2, 3, 7, 8, 9, 16 };
		for (int i = 0; i < columnArr1.length; i++) {
			OrderColumn orderColumn = new OrderColumn();
			orderColumn.setColumn(columnArr1[i]);
			orderColumn.setOrder(orderArr1[i]);
			columns.add(orderColumn);
		}
		tcc.setTableName("userstatus");
		tcc.setColumns(columns);
		tableService.updateCustomColumn(tcc, accountInfo.getId());
		// 添加历史用户默认列
		tcc = new TableCustomColumn();
		columns = new ArrayList<>();
		String columnArr2[] = { "hostname", "mac", "group", "bssid", "ssid", "uptime" };
		int orderArr2[] = { 1, 2, 6, 7, 8, 11 };
		for (int i = 0; i < columnArr2.length; i++) {
			OrderColumn orderColumn = new OrderColumn();
			orderColumn.setColumn(columnArr2[i]);
			orderColumn.setOrder(orderArr2[i]);
			columns.add(orderColumn);
		}
		tcc.setTableName("history");
		tcc.setColumns(columns);
		tableService.updateCustomColumn(tcc, accountInfo.getId());
		return restResult;
	}

	@Override
	@Transactional
	@doLog(description = Tips.LogModifyAccount, key = "#accountInfo.username")
	public RestResult update(AccountInfo accountInfo, User Puser) {
		RestResult restResult = new RestResult();
		String remark = accountInfo.getRemark();
		if (remark.length() > 32) {
			restResult.setErrorCode(1);
			restResult.setErrorMsg(messageSourceUtil.getMessage(Tips.RemarkNotGreaterThan32Letters));
			return restResult;
		}
		// 修改账号
		if(accountInfo.getId() == null || accountInfo.getId() <= 0){
			restResult.setErrorCode(1);
			restResult.setErrorMsg(messageSourceUtil.getMessage(Tips.InvalidParameter));
			return restResult;
		}
		accountMapper.update(accountInfo);
		// 更新权限
		userRoleMapper.deleteByUid(accountInfo.getId());
		List<Integer> auths = accountInfo.getAuths();
		List<Role> basic = roleMapper.queryBasic();
		for (Role role : basic) {
			auths.add(role.getId());
		}
		for (Integer auth : auths) {
			userRoleMapper.save(auth, accountInfo.getId());
		}
		return restResult;
	}

	@Override
	@Transactional
	@doLog(description = Tips.LogDeleteAccount, key = "")
	public RestResult delete(List<Long> ids) {
		RestResult restResult = new RestResult();
		for (long id : ids) {
			userMapper.deleteById(id);
			userRoleMapper.deleteByUid(id);
			customColumnMapper.deleteByUserId(id);
		}
		return restResult;
	}

	// 查找组所有子账号
	@Override
	public List<User> queryChildrenUser(long userId) {
		List<User> result = new ArrayList<>();
		
		List<User> users = userMapper.queryByParentId(userId);
		if (users == null || users.isEmpty()) {
			return null;
		} else {
			for (User user : users) {
				List<User> childrens = queryChildrenUser(user.getId());
				if (childrens != null) {
					result.addAll(childrens);
				}
			}
		}
		result.addAll(users);
		return result;
	}

	@Override
	public Object queryRoleList() {
		List<Role> roles = roleMapper.queryAll();
		SimplePropertyPreFilter roleFilter = new SimplePropertyPreFilter(Role.class, "id", "description", "group",
				"type");
		String json = JSON.toJSONString(roles, roleFilter);
		return JSON.parse(json);
	}

	@Override
	public TableOutput<AccountInfo> queryList(TableInput input, User parent) {
		Map<String, Object> conditions = new HashMap<>();
		conditions.put("searchs", input.getSearch());
		if (input.getOrder() != null) {
			conditions.put("orderColumn", input.getOrder().getColumn());
			conditions.put("orderDirection", input.getOrder().getDir());
		}
		List<User> childrens = queryChildrenUser(parent.getId());
		List<Long> userIds = new ArrayList<>();
		if (childrens != null) {
			for (User user : childrens) {
				userIds.add(user.getId());
			}
		}
		int total = 0;
		List<User> users = null;
		if (userIds.size() > 0) {
			conditions.put("userIds", userIds);
			total = userMapper.countByCondition(conditions);
			conditions.put("start", input.getStart());
			conditions.put("rows", input.getRows());
			users = userMapper.queryByCondition(conditions);
		}
		List<AccountInfo> infos = new ArrayList<>();
		if (users != null) {
			for (User user : users) {
				if (user.getParentId() == null) {
					continue;
				}
				AccountInfo info = new AccountInfo();
				info.convert(user);
				User p = userMapper.queryById(user.getParentId());
				info.setParent(p.getUsername());
				List<Role> auths = userRoleMapper.queryByUid(user.getId());
				List<Integer> as = new ArrayList<>();
				for (Role role : auths) {
					as.add(role.getId());
				}
				String authInfo = getAuthInfo(auths);
				info.setAuthInfo(authInfo);
				info.setAuths(as);
				infos.add(info);
			}
		}
		TableOutput<AccountInfo> output = new TableOutput<>();
		output.setTotal(total);
		output.setRows(input.getRows());
		output.setStart(input.getStart());
		output.setList(infos);
		return output;
	}

	private String getAuthInfo(List<Role> auths) {
		String roleInfo = "";
		for (Role role : auths) {
			roleInfo += role.getDescription() + "，";
		}
		return roleInfo.substring(0, roleInfo.length() - 1);
	}

}
